<template>
  <div class="home">
    <h1>{{ count }}</h1>
    <hr>
    <h2>name: {{ state.name }}</h2>
    <h2>age: {{ state.age }}</h2>
    <h2>wife: {{ state.wife }}</h2>
    <button @click="increase">增加</button>
    <h1>fullName1: {{ fullName1 }}</h1>
    <h1>fullName2: {{ fullName2 }}</h1>
    <h1>fullName3: {{ fullName3 }}</h1>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, reactive, computed, watch, watchEffect, inject} from 'vue';


export default defineComponent({
  name: 'Home',
  setup() {
    const count = ref(1)
    console.log(count)

    const usr = reactive({
      firstName: 'A',
      lastName: 'B'
    })
    const fullName1 = computed(() => {
      console.log('fullName1')
      return usr.firstName + '-' + usr.lastName
    })
    const fullName2 = computed({
      get() {
        console.log('fullName2 get')
        return usr.firstName + '-' + usr.lastName
      },
      set(value: string) {
        console.log('fullName2 set')
        const names = value.split('-')
        usr.firstName = names[0]
        usr.lastName = names[1]
      }
    })
    const fullName3 = ref('')
    watch(usr, () => {
      fullName3.value = usr.firstName + '-' + usr.lastName
    }, {
      immediate: true,
      deep: true
    })
    watch(fullName3, (value => {
      console.log('watch')
      const names = value.split('-')
      usr.firstName = names[0]
      usr.lastName = names[1]
    }))
    watch([() => usr.firstName, () => usr.lastName, fullName3], (value => {
      console.log('监控多个数据源', value)
    }))
    const click = function () {
      console.log('click')
    }
    watchEffect(() => {
      console.log('监控所有回调中使用的数据: watchEffect')
      // document.body.innerHTML = `count: ${count}`
      document.body.addEventListener('click', click)
      fullName3.value = usr.firstName + '-' + usr.lastName
    })

    function increase() {
      count.value = count.value + 1
      state.name += '--'
      state.age += 1
      state.wife.name += '++'
      state.wife.age += 2
      usr.firstName = 'Chan'
    }

    const state = reactive({
      name: 'tom',
      age: 25,
      wife: {
        name: 'marry',
        age: 22
      },
    })
    console.log(state, state.wife)
    const router = inject("$router");
    console.log(router)
    // const number = computed(() => inject("$store").state.number * 2)
    // console.log(number)
    return {
      count,
      increase,
      state,
      fullName1,
      fullName2,
      fullName3
    }
  }
});
</script>
